package com.jsecode.protocol.gid22;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jsecode.lib.util.ByteUtil;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

/**
 * 平台/终端确认应答 0x80 0x7F (平台) 0x81
 *
 * @author grind
 * @date Apr 3, 2014 9:24:51 AM
 * @version 1.0
 */
public class GidUnRsp extends GidBody {
    protected static Logger logger = LoggerFactory.getLogger("gid22-GidUnRsp");

    public static final int RET_SUCESS = 0x00;
    public static final int RET_FAIL = 0x01;
    private int value; // 1. 对用平台确认应答0x80  u8 功能ID 
          // 2. 对于终端确认应答 0x7F
          //    0x00 设置成功
          //    0x01 设置失败
          // 3. 对于平台通知终端确认应答 0x81
          //    0x00 升级受理
          //    0X01 升级包格式错误
          //    0x02 版本相同不升级
          //    0x03 车机掉电暂时不升级
    
    public GidUnRsp(int len) {
        super(len);
    }
    public GidUnRsp(int len, int value){
        super(len);
        this.value = value;
    }
  
    @Override
    public ByteBuf pack(){
        int capacity = 1;
        ByteBuf buf = Unpooled.buffer(capacity);

        buf.writeByte(value);
        packedBuf = buf;
        return buf;
    }
    
    @Override
    public int unpack(ByteBuf srcBuf){
        value = srcBuf.readUnsignedByte();
        return 0;
    }

    public int getValue(){
        return value;
    }

    public void setValue(int value){
        this.value = value;
    }

    @Override
    public String toString(){
        StringBuilder sb = new StringBuilder();
        sb.append("value=").append(value);
        return sb.toString();
    }

    /**
     * 封装平台通用应答协议
     * @param msgHeader
     * @return 返回封装好的数据
     */
    public static ByteBuf packUnRsp (GidHeader msgHeader) {
        GidHeader rspHeader = new GidHeader(msgHeader.getMsgSeq(), GidMsgID.PF_UN_RSP, msgHeader.getDevId()); // header
        GidUnRsp rspBody = new GidUnRsp(1, msgHeader.getMsgId()); // body
        
        GidPack rspPack = new GidPack(rspHeader, rspBody);
        return rspPack.pack();
    }
    
    /** 返回终端的设置结果 */
    public static int unpackResult(ByteBuf srcBuf) {
        if (srcBuf.readableBytes() > 0) {
            return srcBuf.readUnsignedByte();
        }
        return RET_FAIL;
    }

    public static void main(String[] args) {
        // FA FA 4D 80 00 00 C2 82 29 B0 00 01 00 15 FB
        GidHeader msgHeader = new GidHeader((short)0x4D, GidMsgID.GPS_REPORT_FLAG, 3263310256l);
        ByteBuf packedBuf = packUnRsp(msgHeader);
        
        logger.info("packedBuf buf:" + ByteUtil.formatHexStr(packedBuf.array()));
    }
}
